//
//  MainViewController.m
//  QrcodeScanner
//
//  Created by Nguyen Cong Huy on 9/12/14.
//  Copyright (c) 2014 FreeAppForYou. All rights reserved.
//

#import "MainViewController.h"
#import "../ZXing/ZXingObjC/ZXingObjC.h"
#import "ResultViewController.h"
#import "GADBannerView.h"
#import "RateRequestManager.h"
#import "GuideView.h"

#define kGuideViewKey @"kGuideViewKey"

@interface MainViewController () <ZXCaptureDelegate, GADBannerViewDelegate> {
}

@property (nonatomic, strong) ZXCapture *capture;
@property (nonatomic) UIView *focusView;
@property (nonatomic) GADBannerView* bannerView;

@end

@implementation MainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"QR scanner", nil);
    
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    [self checkCameraPrivacy];
    
    [self addView];
    [self showGuideViewIfNecessary];
    
    RateRequestManager* rateRequestManager = [RateRequestManager getInstance];
    rateRequestManager.countToAskRate = 15;
    rateRequestManager.appRateUrlString = @"https://itunes.apple.com/us/app/qr-scanner-lite/id918901674";
    [rateRequestManager updateAndShowRateRequestIfNeed];
}

- (void)addView {
    self.capture = [[ZXCapture alloc] init];
    self.capture.camera = self.capture.back;
    self.capture.focusMode = AVCaptureFocusModeContinuousAutoFocus;
    self.capture.rotation = 90.0f;
    
    self.capture.layer.frame = self.view.bounds;
    [self.view.layer addSublayer:self.capture.layer];
    
    if([self.capture hasTorch]) {
        UIBarButtonItem *torchButtonItem =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"light_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(torchButtonTouched)];
        UIBarButtonItem *questionButtonItem =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"question_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(questionButtonTouched)];
        [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:torchButtonItem, questionButtonItem, nil]];
    }
    
    UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapViewGesture:)];
    [self.view addGestureRecognizer:tapGesture];
    
    self.focusView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 60, 60)];
    self.focusView.backgroundColor = [UIColor clearColor];
    self.focusView.layer.borderColor = RGBCOLOR(0, 143, 249).CGColor;
    self.focusView.layer.borderWidth = 2;
    self.focusView.alpha = 0;
    [self.view addSubview:self.focusView];
    
    self.bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner];
    self.bannerView.adUnitID = @"ca-app-pub-2807844358876629/4938855795";
    self.bannerView.rootViewController = self;
    self.bannerView.delegate = self;
    [self.view addSubview:self.bannerView];
    [self loadAd];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.capture.delegate = self;
    self.capture.layer.frame = self.view.bounds;
    [self.view.layer addSublayer:self.capture.layer];
    
    self.bannerView.frame = CGRectMake(0, self.view.height - self.bannerView.frame.size.height, self.bannerView.frame.size.width, self.bannerView.frame.size.height);
    
    CGAffineTransform captureSizeTransform = CGAffineTransformMakeScale(320 / self.view.frame.size.width, 480 / self.view.frame.size.height);
    self.capture.scanRect = CGRectApplyAffineTransform(self.view.frame, captureSizeTransform);
    
    [self.view bringSubviewToFront:self.focusView];
    [self.view bringSubviewToFront:self.bannerView];
}

- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result {
    if (!result) return;
    self.capture.delegate = nil;
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        ResultViewController* resultVc = [[ResultViewController alloc] init];
        resultVc.content = result.text;
        [self.navigationController pushViewController:resultVc animated:YES];
    }];
    
    // Vibrate
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

- (void)torchButtonTouched {
    self.capture.torch = !self.capture.torch;
}

- (void)questionButtonTouched {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert", nil) message:NSLocalizedString(@"This application help you read content of QR code very fastly. Move your camera to put QR code on screen, this application will scan and read its content. In result screen, you can copy it, or if it is a link, you can open it in Safari.", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Close", nil) otherButtonTitles:nil];
    [alertView show];
}

- (void)tapViewGesture:(UIGestureRecognizer*)gesture {
    CGPoint point = [gesture locationInView:gesture.view];
    [self.capture focusAtPoint:point];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5*NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [self.capture focusAtPoint:point];
    });
    
    [self showFocusViewAtPoint:point];
}

- (void)showFocusViewAtPoint:(CGPoint)point {
    self.focusView.center = point;
    if(self.focusView.alpha == 0) {
        self.focusView.transform = CGAffineTransformMakeScale(1.5, 1.5);
        self.focusView.alpha = 1;
        [UIView animateWithDuration:0.2 animations:^{
            self.focusView.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [self performSelector:@selector(hideFocusView) withObject:nil afterDelay:0.3];
        }];
    }
}

- (void)hideFocusView {
    self.focusView.alpha = 0;
}

- (void)loadAd {
    GADRequest* request = [GADRequest request];
    // iP5: 5e3f
    NSArray* devices = [NSArray arrayWithObjects:GAD_SIMULATOR_ID, @"ffc29db77599977750a25e3e9d895e3f", nil];
    request.testDevices = devices;
    [self.bannerView loadRequest:request];
}

- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error {
    NSLog(@"Fail to receive ad: %@", error);
    
    [self performSelector:@selector(loadAd) withObject:nil afterDelay:20];
}

- (void)checkCameraPrivacy {
    if(SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7")) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if(authStatus == AVAuthorizationStatusAuthorized) {
            NSLog(@"Camera authorized");
        } else if(authStatus == AVAuthorizationStatusDenied){
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert", nil) message:NSLocalizedString(@"You have to accept camera privacy to begin scan. To accept camera, from iPhone's home screen, touch Settings -> Privacy -> Camera -> Turn on QR Scanner", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Close", nil) otherButtonTitles:nil];
            [alertView show];
        }
    }
}

- (void)showGuideViewIfNecessary {
    UIWindow* window = [[UIApplication sharedApplication].windows lastObject];
    GuideView* guideView = [[GuideView alloc] initWithFrame:window.frame userDefaultKey:kGuideViewKey];
    guideView.isAutoScroll = YES;
    [guideView addToSuperViewIfNeed:window];
    
    UIView* pageView = [[UIView alloc] initWithFrame:guideView.frame];
    pageView.backgroundColor = RGBACOLOR(0, 0, 0, 0.8);
    [guideView addPageView:pageView];
    
    int padding = 20;
    UILabel* guideLabel = [[UILabel alloc] initWithFrame:CGRectMake(padding, guideView.height/2, pageView.width - 2*padding, 60)];
    guideLabel.text = NSLocalizedString(@"Move your QR code here \nto begin scan", nil);
    guideLabel.textColor = [UIColor whiteColor];
    guideLabel.backgroundColor = [UIColor clearColor];
    guideLabel.font = [UIFont systemFontOfSize:20];
    guideLabel.textAlignment = NSTextAlignmentCenter;
    guideLabel.numberOfLines = 2;
    [pageView addSubview:guideLabel];
}

@end
